﻿using Basler.Pylon;
using hvppleDotNet;
using HZH_Controls.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HangzhouChipProject
{
    public partial class FrmCamera : FrmWithOKCancel1
    {
        private PixelDataConverter converter = new PixelDataConverter();
        private Camera camera = null;
       List<ICameraInfo> allCameras;
        //List当前选中的相机对象存放
        BaslerCamera Cameradebug;
        //枚举的相机对象
        BaslerCamera baslerCamera1;
        BaslerCamera baslerCamera2;
        BaslerCamera baslerCamera3;
        MainWindows frmMain;
        HTuple hCamsmartwindows1;
        HTuple hCamsmartwindows2;
        HTuple hCamsmartwindows3;
        public FrmCamera(MainWindows mainwindow)
        {
            this.frmMain = mainwindow;
            hCamsmartwindows1 = mainwindow.hSmartWindowControl1.hvppleWindow;
            hCamsmartwindows2 = mainwindow.hSmartWindowControl2.hvppleWindow;
            hCamsmartwindows3 = mainwindow.hSmartWindowControl3.hvppleWindow;
            InitializeComponent();
            this.Title = "相机设置";
            this.IsShowCloseBtn = true;
            this.BackColor = Color.FromArgb(128, 128, 255);
            // DisEable all buttons.
            EnableButtons(false, false);
        }
        protected override void OnClosed(EventArgs e)
        {
            if (Cameradebug==null)
            {
                return;
            }
            Cameradebug.DestroyCamera();
        }
        protected override void DoEnter()
        {
            if (Cameradebug == null)
            {
                return;
            }
            Cameradebug.DestroyCamera();
            base.DoEnter();
        }
        protected override void DoEsc()
        {
            if (Cameradebug == null)
            {
                return;
            }
            Cameradebug.DestroyCamera();
            base.DoEsc();
        }
        private void toolStripButtonOneShot_Click(object sender, EventArgs e)
        {
            Cameradebug.OneShot();
            // The camera is grabbing. Disable the grab buttons. Enable the stop button.
            EnableButtons(false, true);
        }

        private void FrmCamera_Load(object sender, EventArgs e)
        {
            UpdateDeviceList();
        
        }

        private void Camera_CameraImageEvent1(Bitmap bmp)
        {
            HObject  h=  PictureProcess.bitmapToHobject32(bmp);
            PictureProcess.pShowPictureToHwindows(h, hCamsmartwindows1);
        }
        private void Camera_CameraImageEvent2(Bitmap bmp)
        {

            HObject h = PictureProcess.bitmapToHobject32(bmp);
            PictureProcess.pShowPictureToHwindows(h, hCamsmartwindows2);
        }
        private void Camera_CameraImageEvent3(Bitmap bmp)
        {

            HObject h = PictureProcess.bitmapToHobject32(bmp);
            PictureProcess.pShowPictureToHwindows(h, hCamsmartwindows3);
        }

        // Updates the list of available camera devices.
        private void UpdateDeviceList()
        {
            try
            {
                // 列举所有相机.
                 allCameras = CameraFinder.Enumerate();
                ListView.ListViewItemCollection items = deviceListView.Items;
                //循环遍历生成对象
                foreach (ICameraInfo cameraInfo in allCameras)
                {
                    switch (cameraInfo[CameraInfoKey.SerialNumber])
                    {
                        case "40076873":
                            baslerCamera1 = new BaslerCamera(cameraInfo);
                            baslerCamera1.CameraImageEvent += Camera_CameraImageEvent1;                            
                            break;
                        case "40070973":
                            baslerCamera2 = new BaslerCamera(cameraInfo);
                            baslerCamera2.CameraImageEvent += Camera_CameraImageEvent2;
                            break;
                        case "40076874":
                            baslerCamera3 = new BaslerCamera(cameraInfo);
                            baslerCamera3.CameraImageEvent += Camera_CameraImageEvent3;
                            break;

                    }

                    // Loop over all cameras in the list of cameras.
                    bool newitem = true;            
                    foreach (ListViewItem item in items)
                    {
                        ICameraInfo tag = item.Tag as ICameraInfo;

                        // Is the camera found already in the list of cameras?
                        if (tag[CameraInfoKey.FullName] == cameraInfo[CameraInfoKey.FullName])
                        {
                            tag = cameraInfo;
                            newitem = false;
                            break;
                        }
                    }

                    // If the camera is not in the list, add it to the list.
                    if (newitem)
                    {
                        // Create the item to display.
                        ListViewItem item = new ListViewItem(cameraInfo[CameraInfoKey.FriendlyName]);

                        // Create the tool tip text.
                        string toolTipText = "";
                        foreach (KeyValuePair<string, string> kvp in cameraInfo)
                        {
                            toolTipText += kvp.Key + ": " + kvp.Value + "\n";
                        }
                        item.ToolTipText = toolTipText;

                        // Store the camera info in the displayed item.
                        item.Tag = cameraInfo;

                        // Attach the device data.
                        deviceListView.Items.Add(item);
                    }
                }
                // Remove old camera devices that have been disconnected.
                foreach (ListViewItem item in items)
                {
                    bool exists = false;

                    // For each camera in the list, check whether it can be found by enumeration.
                    foreach (ICameraInfo cameraInfo in allCameras)
                    {
                        if (((ICameraInfo)item.Tag)[CameraInfoKey.FullName] == cameraInfo[CameraInfoKey.FullName])
                        {
                            exists = true;
                            break;
                        }
                    }
                    // If the camera has not been found, remove it from the list view.
                    if (!exists)
                    {
                        deviceListView.Items.Remove(item);
                    }
                }
            }
            catch (Exception exception)
            {
                ShowException(exception);
            }
        }

        private void toolStripButtonContinuousShot_Click(object sender, EventArgs e)
        {
            Cameradebug.ContinuousShot();
            EnableButtons(false, true);
        }

        private void toolStripButtonStop_Click(object sender, EventArgs e)
        {
            Cameradebug.Stop();
            EnableButtons(true, false);
        }
        private void deviceListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Destroy the old camera object.
            if (camera != null)
            {
                Cameradebug.DestroyCamera();
            }
            // Open the connection to the selected camera device.
            if (deviceListView.SelectedItems.Count > 0)
            {
                // Get the first selected item.
                ListViewItem item = deviceListView.SelectedItems[0];
                // Get the attached device data.
                ICameraInfo selectedCamera = item.Tag as ICameraInfo;
                try
                {
                    string camera = selectedCamera[CameraInfoKey.SerialNumber];
                    switch (camera)
                    {
                        case "40076873":
                         Cameradebug = baslerCamera1;
                            break;
                        case "40070973":
                            Cameradebug = baslerCamera2;
                            break;
                        case "40076874":
                            Cameradebug = baslerCamera3;
                            break;
                    }

                    EnableButtons(true, false);
                    if (Cameradebug.camera.Parameters.Contains(PLCamera.GainAbs))
                    {
                        gainSliderControl.Parameter = Cameradebug.camera.Parameters[PLCamera.GainAbs];
                    }
                    else
                    {
                        gainSliderControl.Parameter = Cameradebug.camera.Parameters[PLCamera.Gain];
                    }
                    if (Cameradebug.camera.Parameters.Contains(PLCamera.ExposureTimeAbs))
                    {
                        exposureTimeSliderControl.Parameter = Cameradebug.camera.Parameters[PLCamera.ExposureTimeAbs];
                    }
                    else
                    {
                        exposureTimeSliderControl.Parameter = Cameradebug.camera.Parameters[PLCamera.ExposureTime];
                    }
                }
                catch (Exception exception)
                {
                    ShowException(exception);
                }
            }
        }
        // Shows exceptions in a message box.
        private void ShowException(Exception exception)
        {
            MessageBox.Show("Exception caught:\n" + exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        // Helps to set the states of all buttons.
        private void EnableButtons(bool canGrab, bool canStop)
        {
            toolStripButtonContinuousShot.Enabled = canGrab;
            toolStripButtonOneShot.Enabled = canGrab;
            toolStripButtonStop.Enabled = canStop;
        }
    }
}
